package two;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ListAndMapObjectMapper {
    public static void main(String[] args) throws IOException {
        //读取json数组到List
        readJsonArrayToList();
        //读取json对象到Map
        readJsonObjectToMap();

        // 将list写成json
        writeList();
        // 将map写成json
        writeMap();
    }

    private static void writeMap() throws JsonProcessingException {
        HashMap<String, Integer> map = new HashMap<>();
        map.put("A", 1);
        map.put("B", 2);
        map.put("C", 3);
        String json = new ObjectMapper().writeValueAsString(map);
        System.out.println(json);
    }

    private static void writeList() throws JsonProcessingException {
        List<String> list = Arrays.asList("1", "2", "3");
        String json = new ObjectMapper().writeValueAsString(list);
        System.out.println(json);
    }

    private static void readJsonArrayToList() throws IOException {
        URL listJson = ListAndMapObjectMapper.class.getClassLoader().getResource("two/list.json");
        List list = new ObjectMapper().readValue(listJson, List.class);
        System.out.println(list);
    }

    private static void readJsonObjectToMap() throws IOException {
        URL mapJson = ListAndMapObjectMapper.class.getClassLoader().getResource("two/map.json");
        Map map = new ObjectMapper().readValue(mapJson, Map.class);
        System.out.println(map);
    }
}
